package com.gem.factory.user;

import com.gem.entity.User;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author: Xhy
 * CreateTime: 2022-09-21 13:56
 * 存放用户工厂
 */
@Component
public class UserFactory {

    // 用户id  用户名
    private static ConcurrentHashMap<String,String> users = new ConcurrentHashMap<>();


    /**
     * 创建用户
     * @param name
     * @return
     */
    public static String createUser(String name){
        String uId = UUID.randomUUID().toString();
        if (existUser(uId)){
            return uId;
        }
        users.put(uId,name);
        return uId;
    }

    /**
     * 获取用户名
     * @param userId
     * @return
     */
    public static String get(String userId){
        return users.get(userId);
    }
    /**
     * 查询所有用户
     * @return
     */
    public static List<User> listUsers(){
        ArrayList<User> userList = new ArrayList<>();
        for (String key : users.keySet()) {
            User user = new User();
            user.setId(key);
            user.setName(users.get(key));
            userList.add(user);
        }
        return userList;
    }


    /**
     * 是否存在该用户
     * @param userId
     * @return
     */
    public static boolean existUser(String userId){
        if (userId == null){
            return false;
        }

        return users.containsKey(userId);
    }

    /**
     * 删除用户
     * @param userId
     */
    public static void remove(String userId){
        users.remove(userId);
    }

    /**
     * 根据ids查询用户
     * @param userIds
     * @return
     */
    public static List<User> selectUsers(List<String> userIds) {

        ArrayList<User> result = new ArrayList<>();
        for (String id : userIds) {
            User user = new User();
            user.setId(id);
            user.setName(users.get(id));
            user.setType(true);
            result.add(user);
        }
        return result;
    }
}
